/*
 *  Copyright 2011 jmarsden.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package cc.plural.jsonij.jpath;

import java.util.List;

import cc.plural.jsonij.Value;

/**
 * LastIndexPredicate Predicate Implementation. Results in querying the last element
 * of an array during evaluation.
 *
 * @author J.W.Marsden.
 */
public class LastIndexPredicate extends PredicateComponent {

    int offset;
    public static final LastIndexPredicate LAST;

    static {
        LAST = new LastIndexPredicate();
    }

    public LastIndexPredicate() {
        this(0);
    }

    public LastIndexPredicate(int offset) {
        this.offset = Math.abs(offset);
    }

    public boolean hasOffset() {
        return offset != 0;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final LastIndexPredicate other = (LastIndexPredicate) obj;
        if (this.offset != other.offset) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 71 * hash + this.offset;
        return hash;
    }

    @Override
    public List<Value> evaluate(List<Value> values, List<Value> results) {
        if (!hasOffset()) {
            int indexPredicate = -1;
            for(Value value: values) {
                if ((indexPredicate = value.size() - 1) >= 0) {
                    results.add(value.get(indexPredicate));
                }
            }
        } else {
            int indexPredicate = -1;
            for(Value value: values) {
                if ((indexPredicate = value.size() - getOffset()) >= 0) {
                    results.add(value.get(indexPredicate));
                }
            }
        }
        return results;
    }

}
